<template>
  <!-- 大盒子 -->
  <div class="MedicenCata">
    <!-- 主体内容 -->
    <div class="main">
      <!-- left -->
      <div class="main-left">
        <!-- tree -->
        <el-tree
            :data="elTree"
            :props="defaultProps"
            node-key="label"
            :default-expanded-keys="['全部']"
            accordion
            @node-click="handleNodeClick"
            class="custom-tree"
            highlight-current
            :expand-on-click-node="false"
        >
    <span class="custom-tree-node" slot-scope="{ node, data }" style="font-size: 12px;">
						<span :name="node.label">
							<i v-if="!data.children"
                 :class="node.expanded ? 'el-icon-openFile' : 'el-icon-closeFiles'"></i>
							<i v-else class="el-icon-openFile"></i>{{ node.label }}
						</span>
					</span>
        </el-tree>
      </div>
      <!-- right -->
      <div class="main-right" ref="mainRight">
        <!-- tit -->
        <div class="main-icon">
          <div class="main-icon-a">
            <i :class="iconComes"
               style="border-radius: 50%;font-size: 20px;padding: 6px;margin-left: 8px;;background-color: #5a5a5a;color: #fff;"></i>
            <span style="font-size: 12px;font-weight:bold;margin-left: 12px;color: #606266;">{{ CatalogueName }}</span>
          </div>
          <!-- btn1 -->
          <div class="main-icon-b">
            <span style="font-size: 12px;color: #606266;font-weight: bold;">状态：</span>
            <el-dropdown @command="handleCommand" trigger="click">
              <span class="el-dropdown-link">{{ DropDownedName }}<i class="el-icon-down"></i></span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="a">可用</el-dropdown-item>
                <el-dropdown-item command="b">禁用</el-dropdown-item>
                <el-dropdown-item command="c" divided>全部</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <!-- btn2 -->
          <!--          <div class="main-icon-c">
                      <div style="display: inline-block; margin-left: 10px;">
                        <span style="font-size: 12px; color: #606266; font-weight: bold; display: inline-block; min-width: 60px; line-height: 28px;">挂号类型:</span>
                        <el-select
                            v-model="regState"
                            placeholder=""
                            clearable
                            size="mini"
                            @change="handleGetRegList"
                            class="custom-select"
                            style="width:150px">
                          <el-option
                              v-for="item in regOptions"
                              :key="item.id"
                              :label="item.label"
                              :value="item.id">
                          </el-option>
                        </el-select>
                      </div>
                    </div>-->

          <div class="main-icon-c">
            <span
                style="font-size: 12px;color: #606266;font-weight: bold;display: inline-block;width: 68px;">关键字:</span>
            <el-input size="mini" placeholder="模板名称" v-model="searchValue"
                      @keyup.enter.native="handClick(0)"></el-input>
          </div>
          <!-- btn3 -->
          <div class="main-icon-c">
            <el-button v-for="(v,i) in headerBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini"
                       v-if="!v.auth || (Array.isArray(v.auth) && v.auth.every(auth => permissionsArr.includes(auth)))"
                       :style="v.style" @click="handClick(i)">{{ v.title }}
            </el-button>
          </div>
        </div>
        <!-- table -->
        <div class="table">
          <el-table :data="tableData1" v-if="currentTableType === 'tableRows1'" border
                    :style="{ width: windowWidth + 'px' }" @row-dblclick="handleDbShowData">
            <el-table-column v-for="(col, inx) in tableRows1" :key="inx" :type="col.type" :prop="col.prop"
                             :label="col.name" :render-header="labelHead"
                             :min-width="getColumnWidth(col.label,col.prop,tableData1)" header-align="center">

              <template #default="{ row }">
                <!-- 特殊处理状态列（假设prop为'state'） -->
                <template v-if="col.prop === 'state'">
                  <el-tag :type="row.state === '1' ? 'success' : 'danger'"
                          size="small"
                          effect="light"
                          :class="'status-tag status-tag-' + row.state">
                    <i :class="row.state === '1' ? 'el-icon-success' : 'el-icon-error'"></i>
                    {{ row.state === '1' ? '启用' : '禁用' }}
                  </el-tag>
                </template>
                <!-- 其他列保持原样 -->
                <template v-else>
                  {{ safeGetMappedValue(col, row) }}
                </template>
              </template>
            </el-table-column>
            <!-- fixed -->
            <el-table-column fixed="left" label="行号" type="index"></el-table-column>
            <el-table-column fixed="right" label="操作" width="148"
            v-if="['system:complaintemplate:edit', 'system:nowsickness:edit', 'system:history:edit'].every(perm => permissionsArr.includes(perm))"
            >
              <template slot-scope="scope">
                <div class="editbox" style="text-align: center;">
                  <el-button type="primary" @click="handleClickEdit(scope.row)" size="mini">编辑</el-button>
                  <el-button :type="scope.row.state === '1' ? 'danger' : 'success' "
                             @click="handleStartOrDisabled(scope.row)" size="mini">
                    {{ scope.row.state === '1' ? '禁用' : '启用' }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <el-table :data="tableData2" border v-else :style="{ width: windowWidth + 'px' }"
                    @row-dblclick="handleDbShowData">
            <el-table-column v-for="(col, inx) in tableRows2" :key="inx" :type="col.type" :prop="col.prop"
                             :label="col.name" :render-header="labelHead"
                             :min-width="getColumnWidth(col.label,col.prop,tableData1)" header-align="center">

              <template #default="{ row }">
                <!-- 特殊处理状态列（假设prop为'state'） -->
                <template v-if="col.prop === 'state'">
                  <el-tag :type="row.state === '1' ? 'success' : 'danger'"
                          size="small"
                          effect="light"
                          :class="'status-tag status-tag-' + row.state">
                    <i :class="row.state === '1' ? 'el-icon-success' : 'el-icon-error'"></i>
                    {{ row.state === '1' ? '启用' : '禁用' }}
                  </el-tag>
                </template>
                <!-- 其他列保持原样 -->
                <template v-else>
                  {{ safeGetMappedValue(col, row) }}
                </template>
              </template>
            </el-table-column>
            <!-- fixed -->
            <el-table-column fixed="left" label="行号" type="index"></el-table-column>
            <el-table-column fixed="right" label="操作" width="148">
              <template slot-scope="scope">
                <div class="editbox" style="text-align: center;">
                  <el-button type="primary" @click="handleClickEdit(scope.row)" size="mini">编辑</el-button>
                  <el-button :type="scope.row.state === '1' ? 'danger' : 'success' "
                             @click="handleStartOrDisabled(scope.row)" size="mini">
                    {{ scope.row.state === '1' ? '禁用' : '启用' }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 新增模板 -->
        <el-dialog
            :close-on-click-modal="false"
            :title="templateAddRrEditTtiel"
            :before-close="handleCancelTemplate"
            :visible.sync="tpAddOrEditMedicineDialog"
            class="tpAddOrEditMedicineDialog"
            width="600px">

          <div class="dialog-form-container">
            <el-form
                :model="templateForm"
                :rules="templateRules"
                label-width="100px"
                size="mini"
                ref="templateFormRef"
                :disabled="templateDisabled"
                label-position="right">

              <!-- 第一行：名称 + 科室 -->
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="名称：" prop="name">
                    <el-input
                        v-model="templateForm.name"
                        @input="handleNameChangeCode"
                        placeholder="请输入名称"/>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="科室：" prop="deptId">
                    <el-select
                        v-model="templateForm.deptId"
                        placeholder="请选择科室"
                        style="width: 100%">
                      <el-option
                          v-for="item in deptOptions"
                          :key="item.id"
                          :label="item.label"
                          :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 第二行：拼音简码 + 适用范围 -->
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="拼音简码：" prop="pinyin">
                    <el-input
                        :disabled="true"
                        v-model="templateForm.pinyin"
                        placeholder="自动生成"/>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="适用范围：" prop="rangeType">
                    <el-select
                        v-model="templateForm.rangeType"
                        placeholder="请选择适用范围"
                        style="width: 100%">
                      <el-option
                          v-for="item in rangeTypeOption"
                          :key="item.id"
                          :label="item.label"
                          :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 第三行：状态 -->
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="状态：" prop="state">
                    <el-select
                        v-model="templateForm.state"
                        placeholder="请选择状态"
                        style="width: 100%">
                      <el-option
                          v-for="item in templateStateOption"
                          :key="item.id"
                          :label="item.label"
                          :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 主诉内容（文本域） -->
              <el-form-item label="内容:" prop="content">
                <el-input
                    type="textarea"
                    v-model="templateForm.content"
                    :rows="3"
                    placeholder="请输入内容"
                    style="width: 100%"/>
              </el-form-item>

              <!-- 备注（文本域） -->
              <el-form-item label="备注：" prop="remark">
                <el-input
                    type="textarea"
                    v-model="templateForm.remark"
                    :rows="3"
                    placeholder="请输入备注"
                    style="width: 100%"/>
              </el-form-item>




            </el-form>
          </div>
          <div slot="footer" class="dialog-footer no-line">
            <el-button type="primary" size="mini" @click="handleAddTemplate">确定</el-button>
            <el-button size="mini" @click="handleCancelTemplate" style="margin-left: 10px" :disabled="false">取消</el-button>
          </div>
        </el-dialog>
      </div>
    </div>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[8, 16, 24]"
        :page-size="pageSize"
        :total="totalSize"
        layout="total, sizes, prev, pager, next, jumper"
        background
    >
    </el-pagination>
  </div>
</template>

<script>
import AddType from "@/views/reservation/reservationAddType";
import {pinyin} from "pinyin-pro";
import {getDeptList} from "@/api/reservation/reservation";
import {
  addMedicalRecordTemplate,
  getBeforeHistoryTemplate,
  getComplaintemplate, getMedicalRecordTemplate,
  getNowHistoryTemplate,
} from "@/api/reservation/caseHistoryTemplate";
import {
  addBeforeHistoryTemplate,
  addComplainTemplate,
  addNowHistoryTemplate,
  editBeforeHistoryTemplate,
  editComplainTemplate,
  editNowHistoryTemplate, getComplainTemplate, getMedicaltemplate,
} from "@/api/reservation/outpatientPhysician";
import {getDoctorList} from "@/api/scheduling/scheduling";
import {withLoading} from "@/untils/loading";

export default {
  inject: ['reload'], // 无痕刷新
  components: {},
  data() {
    return {
      // 树菜单Props
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // str
      windowWidth: '', //右侧表格动态宽度
      searchValue: '',
      CatalogueName: '病历模板',
      DropDownedName: '全部',
      state: null,
      iconComes: 'el-icon-byj',
      // boolean
      disabled: true,
      getdisabled: true,
      loading: false,
      addModelShow: false, // 新增控制
      showModalVisible: false,
      // number
      idx: 0,
      pageNum: 1, //当前页currentPage
      pageSize: 8,
      totalSize: 10, //总条数
      regState: null,
      currentNode: 1,
      currentTableType: 'tableRows1',

      tpAddOrEditMedicineDialog: false,
      medicalTemplateAddDialogVisible: false,
      templateAddRrEditTtiel: '',
      templateType: null,
      showTemplateData: false,
      rangeTypeOption: [{id: 1, label: '本人'}, {id: 2, label: '本科室'}],
      templateStateOption: [{id: 1, label: '启用'}, {id: 0, label: '禁用'}],
      MedicalTypeOption: [{id: '0', label: '西医病历'}, {id: '1', label: '中医病历'}],
      templateTypeOption: [{id: '0', label: '通用'}, {id: '1', label: '个人'}],
      templateDisabled: false,

      templateRules: {
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'},
          {min: 1, max: 50, message: '长度在1到50个字符', trigger: 'blur'}
        ],
        content: [
          {required: true, message: '请输入内容', trigger: 'blur'},
          {min: 1, max: 500, message: '长度在1到500个字符', trigger: 'blur'}
        ]
      },

      templateForm: {
        id: null,
        content: '',
        deptId: null,
        name: '',
        pinyin: '',
        rangeType: null,
        remark: '',
        state: 1,
      },

      MedicalRecordTemplate: {
        bllx: '',
        bloodPressure: '',
        breathe: '',
        chinaDiagnose: '',
        clqk: '',
        crbs: '',
        fzjc: '',
        gms: '',
        grs: '',
        gthjkjy: '',
        hys: '',
        jbs: '',
        jws: '',
        jzs: '',
        jzxg: '',
        jzzd: '',
        lxbxs: '',
        mblx: '',
        mbmc: '',
        pulse: '',
        qtjc: '',
        sss: '',
        sxs: '',
        temperature: '',
        tgjc: '',
        westernDiagnose: '',
        xbs: '',
        yjz: '',
        zs: '',
      },

      MedicalRecordTemplateRules: {
        bllx: [{required: true, message: '请选择病历类型', trigger: 'blur'}],
        mbmc: [{required: true, message: '请输入模板名称', trigger: 'blur'}],
        mblx: [{required: true, message: '请选择模板类型', trigger: 'blur'}]
      },

      editForm: {}, // form表单 修改 *
      // arr
      data: [],
      userInfo: [],
      tableData1: [],
      tableData2: [],
      currentTable: [],
      showType: [],
      TypeOption: [
        {id: 1, label: '西药', value: '西药'}, {id: 2, label: '中成药', value: '中成药'},
        {id: 3, label: '卫材', value: '卫材'}, {id: 4, label: '血液', value: '血液'},
        {id: 5, label: '疫苗', value: '疫苗'}, {id: 9, label: '中药', value: '中药'}
      ],
      formType: [], // 表单头部内容
      unitStateOption: [{id: 1, label: '启用'}, {id: 0, label: '禁用'}],
      // title右侧按钮
      headerBtn: [
        {search: "search", title: "搜索", type: "success", style: {marginLeft: "-20px"}},
        {add: "add", title: "新增", type: "warning",auth:['system:complaintemplate:add','system:nowsickness:add','system:history:add']},
      ],
      feetBtn: [],
      // title右侧按钮
      tableRows1: [
        {name: "系统序号", prop: "id"}, {name: "名称", prop: "name"},
        {name: "适用范围", prop: "rangeType", op: 'rangeTypeOption'},
        {name: "主诉内容", prop: "content"}, {name: "备注", prop: "remark"},
        {name: "状态", prop: "state", op: "templateStateOption"}, {name: "科室名称", prop: "deptName"},
        {name: "创建人", prop: "createName"}, {name: "创建时间", prop: "createTime"},
        {name: "更新人", prop: "updateId", op: "doctorOptions"}, {name: "更新时间", prop: "updateTime"}
      ],

      tableRows2: [
        {name: "病历类型", prop: "bllx"}, {name: "模板类型", prop: "mblx"},
        {name: "模板名称", prop: "mbmc"},
        {name: "血压", prop: "bloodPressure"}, {name: "西医诊断", prop: "westernDiagnose"},
        {name: "处理情况", prop: "clqk"}, {name: "传染病史", prop: "crbs"},
        {name: "辅助检查", prop: "fzjc"}, {name: "过敏史", prop: "gms"},
        {name: "现病史", prop: "xbs"}, {name: "月经史", prop: "yjz"},
        {name: "主诉", prop: "zs"},
        {name: "个人史", prop: "grs"}, {name: "个体化健康教育", prop: "gthjkjy"},
        {name: "婚育史", prop: "hys"}, {name: "疾病史", prop: "jbs"},
        {name: "既往史", prop: "jws"}, {name: "家族史", prop: "jzs"},
        {name: "手术史", prop: "sss"}, {name: "输血史", prop: "sxs"},
        {name: "急诊诊断", prop: "jzzd"}, {name: "急诊效果", prop: "jzxg"},
        {name: "流行病学史", prop: "lxbxs"}, {name: "脉搏", prop: "pulse"},
        {name: "体温", prop: "temperature"}, {name: "体格检查", prop: "tgjc"},
      ],
      areaOption: [{id: 1, label: '省内'}, {id: 2, label: '省外'}, {id: 3, label: '进口'}],
      stateOption: [{id: 0, label: '禁用'}, {id: 1, label: '可用'}],
      untAtteOption: [{id: 3, label: '合约单位'}],
      regOptions: [],
      doctorOptions: [],
      deptOptions: [],
      roleOptions: [],

      addUnitModalVisible: false, // 布尔值，控制模态框显示
      addUnitType: [],
      addUnitForm: {
        id: null,
        code: '',
        state: 1,
        area: 1,
        name: '',
        pyCode: '',
        bankName: '',
        bankNo: '',
        splerPmtno: '',
        legalRepe: '',
        mainConer: '',
        conerPhone: '',
        conerTel: '',
        conerQq: '',
        conerFax: '',
        conerPostc: '',
        url: '',
        conerMail: '',
        untAtte: 3,
        uscc: '',
        conerAdd: '',
        remark: ''
      },
      showForm: {
        id: null,
        code: '',
        state: 1,
        area: 1,
        name: '',
        pyCode: '',
        bankName: '',
        bankNo: '',
        splerPmtno: '',
        legalRepe: '',
        mainConer: '',
        conerPhone: '',
        conerTel: '',
        conerQq: '',
        conerFax: '',
        conerPostc: '',
        url: '',
        conerMail: '',
        untAtte: 3,
        uscc: '',
        conerAdd: '',
        remark: ''
      },
      addUnitRules: {
        code: [{required: true, message: '请填写合约单位编码！', trigger: 'change'}],
        name: [{required: true, message: '请填写合约单位名称！', trigger: 'change'}],
      },
      elTree: [
        {
          label: '全部',
          path: '',
          title: '',
          icon: 'el-icon-news',
          children: [
            {label: '主诉', id: 1, tableType: 'tableRows1'},
            {label: '既往史', id: 2, tableType: 'tableRows1'},
            {label: '现病史', id: 3, tableType: 'tableRows1'},
          ]
        }

      ],
      permissionsArr:[],
    };
  },
  mounted() {
    this.addUnitType = AddType.map(function (v) {
      return v
    })
    this.loadData(1);
    this.getDeptList()
    this.getDoctorList()
    this.permissionsArr = JSON.parse(localStorage.getItem('permissions'))
    this.$nextTick(() => {
      this.updateWindowWidth();
      window.addEventListener('resize', this.updateWindowWidth);
    })
  },
  methods: {
    handleAddMedicalTemplate() {
      this.$refs.medicalRecordForm.validate(async (valid) => {
        if (valid) {
          try {
            const res = await addMedicalRecordTemplate(this.medicalRecordForm);
            if (res.code === 200) {
              this.handleCloseAddMedicalTemplate();
            }
          } catch (error) {
            this.$message.error("系统异常:请联系管理员")
          } finally {

          }
        } else {
          // 表单验证失败
          this.$message.error('请检查表单填写是否正确');
          return false;
        }
      });
    },

    handleCloseAddMedicalTemplate() {
      this.medicalTemplateAddDialogVisible = false;
      this.$refs.medicalRecordForm.resetFields();
      this.medicalRecordForm = {};
    },
    async getDeptList() {
      const res = await getDeptList()
      this.deptOptions = res.data.map(item => {
        return {id: item.id, label: item.deptName}
      })
    },

    async getDoctorList() {
      const res = await getDoctorList()
      this.doctorOptions = res.data.map(item => {
        return {id: item.id, label: item.fullName}
      })
    },

    async handleAddTemplate(skipValidation = false) {
      await withLoading(this, '数据提交中...')(async () => {
        // 1. 表单验证（根据参数决定是否跳过）
        if (!skipValidation) {
          const valid = await this.$refs.templateFormRef.validate();
          if (!valid) {
            this.$message.warning('请填写完整表单');
            return;
          }
        }

        // 2. 根据模板类型处理
        switch (this.templateType) {
          case 1:
            const apiCall = this.templateForm.id
                ? editComplainTemplate
                : addComplainTemplate;

            const res1 = await apiCall(this.templateForm);

            if (res1.code === 200) {
              this.tpAddOrEditMedicineDialog = false;
              this.templateForm = Object.assign({}, this.$options.data.call(this).templateForm)
              await this.loadData(1);
            } else {
              this.$message.error(res1.message)
            }
            break;

          case 2: // 既往史模板
            const apiCall3 = this.templateForm.id
                ? editBeforeHistoryTemplate
                : addBeforeHistoryTemplate;

            const res3 = await apiCall3(this.templateForm);
            if (res3.code === 200) {
              this.tpAddOrEditMedicineDialog = false;
              this.templateForm = Object.assign({}, this.$options.data().templateForm);
              await this.loadData(2);
            } else {
              this.$message.error(res3.message)
            }
            break;

          case 3: // 现病史模板
            const apiCall2 = this.templateForm.id
                ? editNowHistoryTemplate
                : addNowHistoryTemplate;

            const res2 = await apiCall2(this.templateForm);
            if (res2.code === 200) {
              this.tpAddOrEditMedicineDialog = false;
              this.templateForm = Object.assign({}, this.$options.data().templateForm);
              await this.loadData(3);
            } else {
              this.$message.error(res2.message)
            }
            break;


        }
      });
    },


    handleStartOrDisabled(row) {
      this.templateForm = JSON.parse(JSON.stringify(row));
      this.templateForm.state = row.state === '1' ? '0' : '1';
      switch (this.currentNode) {
        case 1:
          this.templateType = 1;
          break;

        case 2:
          this.templateType = 2;
          break;

        case 3:
          this.templateType = 3;
          break;
      }
      this.handleAddTemplate(true);
    },

    handleClickEdit(row) {
      switch (this.currentNode) {
        case 1:
          this.templateAddRrEditTtiel = "编辑主诉模板";
          this.templateType = 1;
          break;

        case 2:
          this.templateAddRrEditTtiel = "编辑既往史模板";
          this.templateType = 2;
          break;

        case 3:
          this.templateAddRrEditTtiel = "编辑现病史模板";
          this.templateType = 3;
          break;
      }
      this.templateForm = JSON.parse(JSON.stringify(row));
      this.templateForm.state = parseInt(this.templateForm.state)
      this.showTemplateData = true;
      this.tpAddOrEditMedicineDialog = true;
    },

    handleDbShowData(row) {
      switch (this.currentNode) {
        case 1:
          this.templateAddRrEditTtiel = "查看主诉模板";
          break;

        case 2:
          this.templateAddRrEditTtiel = "查看既往史模板";
          break;

        case 3:
          this.templateAddRrEditTtiel = "查看现病史模板";
          break;
      }
      this.templateForm = row;
      this.templateDisabled = true;
      this.tpAddOrEditMedicineDialog = true;
    },


    handleNameChangeCode() {
      this.templateForm.pinyin =
          pinyin(this.templateForm.name, {pattern: 'first', toneType: 'none', separator: ''}).toLocaleUpperCase();
    },

    handleCancelTemplate() {
      this.loadData(this.currentNode)
      this.templateFormRef = Object.assign({}, this.$options.data.call(this).templateFormRef || {});
      if (this.$refs.templateFormRef) this.$refs.templateFormRef.clearValidate();
      this.templateDisabled = false;
      this.tpAddOrEditMedicineDialog = false;
    },

    safeGetMappedValue(col, row) {
      // 1. 检查数据有效性
      const rawValue = row[col.prop];
      if (rawValue === null || rawValue === undefined) return ' ';

      // 2. 检查映射数组
      const mapArray = this[col.op];
      if (!col.op || !Array.isArray(mapArray)) return rawValue;

      // 3. 执行映射
      const matched = mapArray.find(item => item.id === rawValue);
      return matched?.label || rawValue;
    },

    async loadData(val) {
      val = val === null || val === undefined  ? 1 : val;
      console.log(val,'valvalvalvalval')
      // 定义API映射关系
      const apiMap = {
        1: getComplaintemplate,
        2: getBeforeHistoryTemplate,
        3: getNowHistoryTemplate,
      };

      // 公共请求参数
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        state: this.state ?? null,
        condition: this.searchValue || ''
      };

      try {
        // 根据val值调用对应的API
        const res = await apiMap[val](params);

        if (res.code !== 200) {
          this.$message.error(res.message || '请求失败');
          return;
        }

        // 根据val值决定数据放入哪个表格
        if (val === 4) {
          // 病历数据放入tableData2
          this.tableData2 = res.data.content;
          this.totalSize = res.data.totalSize;
        } else {
          // 其他数据放入tableData1
          this.tableData1 = res.data.content;
          this.totalSize = res.data.totalSize;
        }

      } catch (error) {
        console.error('加载数据出错:', error);
        this.$message.error('系统异常:请联系管理员!');
      }
    },
    /*
      about tree
    */
    handleNodeClick(data, e) {
      this.currentTableType = data.id === 4 ? 'tableRows2' : 'tableRows1';
      this.currentNode = e.data.id;
      this.searchValue = '';
      this.loadData(data.id)
    },

    // SelectVal to editForm
    // col 里面包含了表头字段和名称，list 是表格数据
    columnWidth(col, list) {
      let prop = col.prop, lab = col.lab;
      let width = 40; // 设定一个最小值
      let maxlenStr = ""; // 最长字符串
      for (let info of list) {
        if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
      }
      width = Math.max(width, len(lab), len(maxlenStr));
      // 表格自带的内边距(20px) 自调
      return width + 12; // 这里加了 12px
      function len(str) {
        // 实际分配长度可根据需要自行调整
        let length = 8;
        for (const char of str + "") {
          // 英文小写字符 8px
          if ("a" <= char && char <= "z") length += 8;
          // 英文大写字符 8px
          else if ("A" <= char && char <= "Z") length += 8;
          // 中文字符 28px
          else if (char >= "\u4e00" && char <= "\u9fa5") length += 32;
          // 其他 8px
          else length += 12;
        }
        return length;
      }
    },

    // 步骤
    async handClick(i) {
      switch (i) {
        case 0:
          switch (this.currentNode) {
            case 1:
              let res1 = await getComplaintemplate({
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                state: this.state == null ? null : this.state,
                condition: this.searchValue === '' ? '' : this.searchValue
              });
              if (res1.code === 200) {
                this.$message({
                  type: 'success',
                  message: '查询成功！',
                });
                this.tableData1 = res1.data.content;
                this.totalSize = res1.data.totalSize;
              } else {
                this.$message({
                  type: 'error',
                  message: res1.message,
                });
              }
              break;

            case 2:
              let res2 = await getBeforeHistoryTemplate({
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                state: this.state == null ? null : this.state,
                condition: this.searchValue === '' ? '' : this.searchValue
              });
              if (res2.code === 200) {
                this.$message({
                  type: 'success',
                  message: '查询成功！',
                });
                this.tableData1 = res2.data.content;
                this.totalSize = res2.data.totalSize;
              } else {
                this.$message({
                  type: 'error',
                  message: res2.message,
                });
              }
              break;


            case 3:
              let res3 = await getNowHistoryTemplate({
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                state: this.state == null ? null : this.state,
                condition: this.searchValue === '' ? '' : this.searchValue
              });
              if (res3.code === 200) {
                this.$message({
                  type: 'success',
                  message: '查询成功！',
                });
                this.tableData1 = res3.data.content;
                this.totalSize = res3.data.totalSize;
              } else {
                this.$message({
                  type: 'error',
                  message: res3.message,
                });
              }
              break;
          }
          break;
        case 1:
          this.tpAddOrEditMedicineDialog = true;
          this.showTemplateData = true;
          this.templateForm = Object.assign({}, this.$options.data.call(this).templateForm)
          this.templateAddRrEditTtiel = this.currentNode === 1 ? '新增主诉模板' : this.currentNode === 2 ? '新增既往史模板' : this.currentNode === 3 ? '新增现病史模板' : '';
          this.templateType = this.currentNode;
          break;
      }
    },
    getCurrentNode() {
      // 获取当前选中的节点
      return this.$refs.treeRef.getCurrentKey();
    },

    async handleCommand(command) {
      this.state = command === 'a' ? 1 : command === 'b' ? 0 : command === 'c' ? null : null;
      this.DropDownedName = command === 'a' ? '可用' : command === 'b' ? '禁用' : '全部';
      switch (this.currentNode) {
        case 1:
          let res1 = await getComplaintemplate({
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            state: this.state == null ? null : this.state,
            condition: this.searchValue === '' ? '' : this.searchValue
          });
          if (res1.code === 200) {
            this.$message({
              type: 'success',
              message: '查询成功！',
            });
            this.tableData1 = res1.data.content;
            this.totalSize = res1.data.totalSize;
          } else {
            this.$message({
              type: 'error',
              message: res1.message,
            });
          }
          break;

        case 2:
          let res2 = await getBeforeHistoryTemplate({
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            state: numericValue == null ? null : numericValue,
            condition: this.searchValue === '' ? '' : this.searchValue
          });
          if (res2.code === 200) {
            this.$message({
              type: 'success',
              message: '查询成功！',
            });
            this.tableData1 = res2.data.content;
            this.totalSize = res2.data.totalSize;
          } else {
            this.$message({
              type: 'error',
              message: res2.message,
            });
          }
          break;


        case 3:
          let res3 = await getNowHistoryTemplate({
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            state: numericValue == null ? null : numericValue,
            condition: this.searchValue === '' ? '' : this.searchValue
          });
          if (res3.code === 200) {
            this.$message({
              type: 'success',
              message: '查询成功！',
            });
            this.tableData1 = res3.data.content;
            this.totalSize = res3.data.totalSize;
          } else {
            this.$message({
              type: 'error',
              message: res3.message,
            });
          }
          break;
      }
    },

    feetHandClick(i) {
      console.log(i)
      switch (i) {
        case 0:

          break;
        case 1:

          break;
        case 2:
          break;
        case 3:

          break;
        case 4:

          break;
        case 5:
          break;
      }
    },

    // 实时宽度
    updateWindowWidth() {
      this.windowWidth = window.innerWidth - 328;
    },


    //分页
    //每页条数改变触发
    handleSizeChange(val) {
      this.pageSize = val;
      this.pageNum = 1;
      this.loadData();
    },
    //当前条数改变触发
    handleCurrentChange(val) {
      this.pageNum = val;
      this.loadData();
    },
    getColumnWidth(label, prop, tableData1) {
      const minWidth = 80;
      const padding = 20; // 增加边距缓冲
      const contentList = tableData1.map(item => item?.[prop] ?? '');

      // 计算所有内容宽度（包括表头）
      const widths = [...contentList, label].map(text => {
        const str = String(text || '');
        return this.getTextWidth(str) + padding;
      });

      return Math.max(minWidth, ...widths);
    },

    // 精确计算文本宽度（使用Canvas）
    getTextWidth(text, fontSize = 14) {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      ctx.font = `${fontSize}px Microsoft YaHei`;
      return ctx.measureText(text).width;
    },

    labelHead(h, {column, $index}) {
      let l = column.label.length;
      let f = 12;
      column.minWidth = f * (l + 5); //加上一个文字长度
      return h("div", {class: "table-head", style: {width: "100%"}}, [
        column.label,
      ]);
    },
  }
}
</script>

<style lang="less" scoped>
/* 紧凑表单样式 */
.compact-form {
  margin-top: -15px;
}

.compact-form .el-form-item {
  margin-bottom: 12px;
}

.compact-form .el-form-item__label {
  float: left;
  padding-right: 10px;
  line-height: 28px;
  width: auto !important;
}

.compact-form .el-form-item__content {
  margin-left: 0 !important;
  display: flex;
}

.compact-form .el-textarea {
  flex: 1;
}

.compact-form .el-textarea .el-textarea__inner {
  min-height: 28px !important;
  line-height: 1.4;
  padding: 5px 10px;
}

.dialog-footer {
  margin-top: -10px;
}


/* 关键修改部分 */
.tree-container {
  height: auto; /* 改为自动高度 */
  min-height: 100%; /* 确保最小高度填满 */
  overflow: visible; /* 允许内容溢出 */
}

.custom-tree {
  height: auto !important; /* 强制取消固定高度 */
  overflow: visible !important; /* 禁用滚动条 */
  width: 100%;
}

/* 保留你的原有样式 */
.custom-tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 6px 0;
}

.node-content {
  display: flex;
  align-items: center;
}



.node-label {
  font-size: 12px;
  color: #333;
}

/deep/ .el-dialog__header {
  padding: 18px;
  background-color: #007bb0;
}

/deep/ .el-dialog__title {
  font-size: 18px;
  color: #fff;
}

/deep/ .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

.dialog {
  .showDialog {
    .tabs {
      /deep/ .el-select > .el-input {
        width: 172px;
      }

      /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner {
        width: 172px;
      }

      /deep/ .el-form-item__content {
        display: flex;

        span {
          font-size: 12px;
        }
      }

      .oneLine {
        width: 524px;
        // background-color: indianred;
      }
    }

    /deep/ .el-dialog__title {
      font-size: 15px;
    }

    /deep/ .el-table {
      font-size: 15px;
    }
  }
}


// content
.MedicenCata {
  height: 100%;
  width: 100%;
  // header
  .header {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 40px;
    background-color: #efefef;
    padding: 4px;

    // justify-content: space-evenly;
    // icon
    .header-icon {
      display: flex;
      align-items: center;
    }

    .feetbtn {
      display: flex;
      justify-content: center;
      margin-left: 12px;
    }
  }

  // main
  .main {
    width: 100%;
    display: flex;
    justify-content: space-between;
    // height: 473px; /* 设置父容器的高度 */
    // overflow-y: auto; /* 当内容超出容器高度时显示垂直滚动条 */
    // left
    .main-left {
      .custom-tree {
        max-height: 100%; /* 设置树形菜单的最大高度为父容器的100% */
        overflow-y: auto; /* 当内容超出设定高度时显示滚动条 */
      }

      /deep/ .el-tree-node__content {
        // height: 40px;
        // padding-right: 8px !important;
      }

      /deep/ .el-tree-node__label {
        font-size: 12px;
      }

      width: 128px;
      height: 100%;
    }

    // right
    .main-right {
      flex: 4;
      height: 100%;
      // alert
      .addmessagesBox {
        .tabs {
          /deep/ .el-select > .el-input {
            width: 172px;
          }

          /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner {
            width: 172px;
          }

          /deep/ .el-form-item__content {
            display: flex;

            span {
              font-size: 12px;
            }
          }

          .oneLine {
            width: 524px;
            // background-color: indianred;
          }
        }

        /deep/ .el-dialog__title {
          font-size: 12px;
        }

        /deep/ .el-table {
          font-size: 12px;
        }

      }

      // icon
      .main-icon {
        display: flex;
        align-items: center;
        padding: 12px;
        line-height: 40px;

        .main-icon-a {
          // width: 240px;
          // background-color: #00557f;
        }

        .main-icon-b {
          margin-left: 28px;

          /deep/ .el-dropdown {
            font-size: 12px;
            cursor: pointer;
          }

          /deep/ .el-dropdown:hover {
            font-weight: bold;
            color: #66b1ff;
          }

          /deep/ .el-icon--right {
            // background-color: #66b1ff;
          }

          /deep/ .el-popper[x-placement^=bottom] {
            margin-top: 0;
          }
        }

        // c
        .main-icon-c {
          display: flex;
          margin-left: 28px;

          /deep/ [data-v-2bacc09b] .el-color-picker__icon, .el-input[data-v-2bacc09b], .el-textarea[data-v-2bacc09b] {
            width: 70%;
          }
        }
      }

      // table
      /deep/ .el-table .cell {
        font-size: 12px;
        text-align: center;
      }

      /deep/ .el-table td.el-table__cell div :first-child {
        text-align: center;
      }

      /deep/ .el-table td.el-table__cell div {
        text-align: center;
        overflow: hidden;
        white-space: normal;
        word-break: break-all;
      }

      .table {

      }
    }
  }

  // addModel
  .addModel {
    margin-left: 12px;

    /deep/ .el-dialog__header {
      padding: 12px;
      line-height: 28px;
      background-color: #007bb0;
    }

    /deep/ .el-dialog__title {
      color: #fff;
      font-size: 12px;
    }

    /deep/ .el-dialog__headerbtn .el-dialog__close {
      color: #fff;
    }

    /deep/ .el-dialog__headerbtn .el-dialog__close:hover {
      background-color: brown;
    }

    /deep/ .el-form-item__label {
      font-size: 12px;
    }
  }

  .editModel {
    /deep/ .el-dialog__header {
      padding: 12px;
      line-height: 28px;
      background-color: #007bb0;
    }

    /deep/ .el-dialog__title {
      color: #fff;
      font-size: 12px;
    }

    /deep/ .el-dialog__headerbtn .el-dialog__close {
      color: #fff;
    }

    /deep/ .el-dialog__headerbtn .el-dialog__close:hover {
      background-color: brown;
    }

    /deep/ .el-form-item__label {
      font-size: 12px;
    }
  }

  // feet
  .feet {
    padding: 12px;

  }

}
</style>